import Vue from 'vue';
import Vuex from 'vuex';

import axios from 'axios';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: 'xxx',
    viewKey: 'all'
  },
  mutations: {
    initList(state, list) {
      state.list = list;
    },

    // 设置
    setInputValue(state, val) {
      state.inputValue = val;
    },

    // 添加任务项
    addItem(state) {
      const obj = {
        id: state.list.length,
        info: state.inputValue.trim(),
        done: false
      };
      state.list.push(obj);
    },

    // 根据id删除对应的任务项
    removeItemById(state, id) {
      const index = state.list.findIndex(x => x.id === id);
      if (index !== -1) {
        // 删除数组中的元素, 从index位置开始删除1个元素
        state.list.splice(index, 1);
      }
    },

    // 修改列表项的选中状态
    changeStatus(state, param) {
      console.log(param);
      const index = state.list.findIndex(item => item.id === param.id);

      if (index !== -1) {
        // 更新列表项
        state.list[index].done = param.status;
      }
    },

    // 清除已完成的任务
    clearDone(state) {
      // 过滤done为true的(已完成)的任务项
      state.list = state.list.filter(item => item.done === false);
    },

    // 修改key
    changeViewKey(state, key) {
      state.viewKey = key;
    }



  },
  actions: {
    getList(context) {
      axios.get('/list.json').then(({data}) => {
        context.commit('initList', data);
        // console.log(data);
      })
    }
  },
  getters: {
    // 统计未完成的任务条数
    getUnDoneCOunt(state) {
      return state.list.filter(item => item.done === false).length;
    },

    infoList(state) {
      if (state.viewKey === 'all') {
        return state.list;
      }
      if (state.viewKey === 'undone') {
        return state.list.filter(x => !x.done);
      }
      if (state.viewKey === 'done') {
        return state.list.filter(x => x.done);
      }
      return state.list;
    },


  },
  modules: {
  }
})
